﻿using System;
using System.Diagnostics; 
using System.Threading;
using System.Windows;

namespace HsServerHa.Monitor
{
    internal class Program
    {
        private static string FilePath = "D:\\net472\\MaterialDesignDemo.exe"; // 指定要监控的程序名称
        private static string FileName = "MaterialDesignDemo"; // 指定要监控的程序名称
        private static Process wpfProcess;
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0) //打印出参数
            {
                int i = 0;
                foreach (var item in args)
                {
                    Console.WriteLine(item);
                    FileName = args[0];
                    FilePath = args[1];
                    i++;
                }
            }
            while (true)
            {
                if (!IsProcessRunning(FileName))
                {
                    //LoggerHelper.Info($"WPF process '{FileName}' is not running. Restarting...");
                    StartWPFProgram();
                }

                Thread.Sleep(5000); // 每隔5秒检查一次WPF进程是否在运行
            }
        }
        private static void StartWPFProgram()
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = FilePath; // 替换为您的WPF程序的路径
            Process.Start(startInfo);
        }


        /// <summary>
        /// 检查程序是否运行
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static bool IsProcessRunning(string FileName)
        {
            //LoggerHelper.Info($"{FileName}");
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (process.ProcessName == FileName)
                {
                    //LoggerHelper.Info($"存在！");
                    return true;
                }
            }
            //LoggerHelper.Info($"不存在！");
            return false;
        }
    }
}
